package com.wang.study.controller;

import com.alibaba.fastjson.JSONObject;
import com.wang.study.Proxy.JdkDynamicProxyUtil;
import com.wang.study.commons.BaseServlet;
import com.wang.study.commons.CommonsUtils;
import com.wang.study.model.User;
import com.wang.study.service.UserService;
import com.wang.study.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/user.do")
public class UserController extends BaseServlet {
    //动态代理使用
    private UserService userService=new JdkDynamicProxyUtil<UserService>().getProxyObject(new UserServiceImpl());
    /**
     * 处理注册时的用户验证
     * @param req
     * @param resp
     */
    public void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        Boolean flag = userService.checkUserName(username);
        //flag=true   找到    不能被注册
        //flag=false 找不到   可以注册
        resp.getWriter().write(new JSONObject().toJSONString(flag));
    }

    /**
     * 处理注册邮箱是否被使用
     * @param req
     * @param resp
     * @throws IOException
     */
    public void checkEmail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String email = req.getParameter("email");
        Boolean flag = userService.checkEmail(email);
        resp.getWriter().write(new JSONObject().toJSONString(flag));
    }

    /**
     * 处理注册密码为空的信息
     * @param req
     * @param resp
     */
    public void checkPassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String password = req.getParameter("password");
        Boolean flag = userService.checkPassword(password);
        resp.getWriter().write(new JSONObject().toJSONString(flag));
    }
    /**
     * 控制层：处理注册业务
     * @param req
     * @param resp
     * @return
     */
    public String register(HttpServletRequest req,HttpServletResponse resp){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        User user = new User(username,CommonsUtils.getMD5(password),email, CommonsUtils.getRandomString(64));
        //调用业务层 跳转路径
        Map<String,String> map = userService.register(user);
        return map.get("path");
    }

    /**
     * 注册时的激活码，激活
     * @param req
     * @param resp
     * @return
     */
    public String active(HttpServletRequest req,HttpServletResponse resp){
        String activeCode = req.getParameter("activeCode");
        userService.active(activeCode);

        //一般只可能激活成功，不存在激活失败案例
        return "r:/commons/login.jsp";
    }

    /**
     * 登录操作
     * @param req
     * @param resp
     * @return
     */
    public String login(HttpServletRequest req,HttpServletResponse resp){

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User(username, CommonsUtils.getMD5(password));
        //获取业务层信息 会话跟踪：user      错误信息：message
        //             是否激活：isSuccess  跳转路径：path
        Map<String,Object> map=userService.login(user);
        //是否激活
        if(!Boolean.valueOf(map.get("isSuccess").toString())){//没激活
            //设置请求信息 出错原因信息
            req.getSession().setAttribute("message",map.get("message").toString());
        }else{
            //设置会话跟踪
            req.getSession().setAttribute("loginUser",map.get("user"));
        }
        //返回跳转路径
        return map.get("path").toString();
    }

    /**
     * 查询所有的用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void findUserAll(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        List<User> users=userService.findUserAll();
        resp.getWriter().write(new JSONObject().toJSONString(users));
    }
    /**
     * 更新用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void updateUserById(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String account = req.getParameter("name");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String status = req.getParameter("status");
        String id = req.getParameter("id");
        Integer i=userService.updateUserById(account,password,email,Integer.valueOf(status),Integer.valueOf(id));
        resp.getWriter().write(new JSONObject().toJSONString(i));
    }
    /**
     * 添加用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void addUser(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String account = req.getParameter("name");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String status = req.getParameter("status");
        Integer i=userService.addUser(account,password,email,Integer.valueOf(status));
        resp.getWriter().write(new JSONObject().toJSONString(i));
    }
    /**
     * 删除用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void delUserById(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        Integer i=userService.delUserById(Integer.valueOf(id));
        resp.getWriter().write(new JSONObject().toJSONString(i));
    }
    //发邮件更新密码
    public String repwd(HttpServletRequest req,HttpServletResponse resp){
       return "r:/commons/repwd.jsp";
    }
    public void repwdEmail(HttpServletRequest req,HttpServletResponse resp){
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        User u=userService.selectUserByUsername(username);
        System.out.println(u.getActiveCode());
        //发邮件 用于用户设置密码
        CommonsUtils.getSendMail("yalishanda345@163.com",u.getEmail(),"JHCJMQJGQWWCNKDA",
                "邮件激活","点击链接<a href='http://127.0.0.1:8080/user.do?method=updatePwd&username="+username+"&pwd="+pwd+"'>"+u.getActiveCode()+"</a>");
    }
    public String updatePwd(HttpServletRequest req,HttpServletResponse resp){
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        Integer i = userService.updatePwd(username,CommonsUtils.getMD5(pwd));
        return i>0?"r:/commons/login.jsp":"r:/commons/register.jsp";
    }
    //注销
    public String backLoginUser(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        req.removeAttribute("loginUser");
        return "r:/commons/login.jsp";
    }
}
